def draw_board(the_board):
""" Draw a chess board with queens, as determined by the the_board. """
pygame.init()
colors =[(255,0,0),(0,0,0)]# Set up colors [red, black]
n =len(the_board)# This is an NxN chess board.
surface_sz =480# Proposed physical surface size.
sq_sz = surface_sz // n # sq_sz is length of a square.
surface_sz = n * sq_sz # Adjust to exactly fit n squares.
surface = pygame.display.set_mode((surface_sz, surface_sz))
ball = pygame.image.load("queen.jpg")
ball_offset =(sq_sz-ball.get_width()) // 2whileTrue:
# Look for an event from keyboard, mouse, etc.
ev = pygame.event.poll()if ev.type== pygame.QUIT:
break;# Draw a fresh background (a blank chess board)for row inrange(n): # Draw each row of the board.
c_indx = row % 2# Alternate starting colorfor col inrange(n): # Run through cols drawing squares
the_square =(col*sq_sz, row*sq_sz, sq_sz, sq_sz)
surface.fill(colors[c_indx], the_square)# Now flip the color index for the next square
c_indx =(c_indx + 1) % 2# Now that squares are drawn, draw the queens.for(col, row)inenumerate(the_board):
surface.blit(ball,(col*sq_sz+ball_offset,row*sq_sz+ball_offset))
pygame.display.flip()
pygame.quit()def col_clashes(bs, c):
""" Return True if the queen at column c clashes
with any queen to its left.
"""for i inrange(c): # Look at all columns to the left of cif share_diagonal(i, bs[i], c, bs[c]):
returnTruereturnFalse# No clashes - col c has a safe placement.def share_diagonal(x0, y0, x1, y1):
""" Is (x0, y0) on a shared diagonal with (x1, y1)? """
dy =abs(y1 - y0)# Calc the absolute y distance
dx =abs(x1 - x0)# CXalc the absolute x distancereturn dx == dy # They clash if dx == dyprint(col_clashes([0,1],1))def has_clashes(the_board):
""" Determine whether we have any queens clashing on the diagonals.
We're assuming here that the_board is a permutation of column
numbers, so we're not explicitly checking row or column clashes.
"""for col inrange(1,len(the_board)):
if col_clashes(the_board, col):
returnTruereturnFalseimportrandomimport pygame
rng =random.Random()# Instantiate a generator
bd =list(range(8))# Generate the initial permutation
num_found =0
tries =0while num_found <10:
rng.shuffle(bd)
tries +=1ifnot has_clashes(bd):
raw_input("Press Enter to continue...")
draw_board(bd)
tries =0
num_found +=1